package com.hbzjt2012.demo01;

import org.apache.commons.io.FileUtils;

import java.io.File;
import java.io.IOException;
import java.net.URL;

//练习Thread，实现多线程同步下载图片
public class TestThread2Runnable implements Runnable{
    private String url;     //网络图片地址
    private String name;    //保存的文件名

    public TestThread2Runnable(String url, String name){
        this.url = url;
        this.name = name;
    }

    //下载图片线程的执行体
    @Override
    public void run() {
        WebDownloaderRunnable webDownloader = new WebDownloaderRunnable();
        webDownloader.downloader(url, name);
        System.out.println("下载的文件名为：" + name);
    }

    public static void main(String[] args) {
        TestThread2Runnable t1 = new TestThread2Runnable("https://cdn.lixingyong.com/2021/10/28/t0194a1161f2ce1524e.jpg", "test1.jpg");
        TestThread2Runnable t2 = new TestThread2Runnable("https://cdn.lixingyong.com/2021/10/28/t01054da51d6beb507c.jpg", "test2.jpg");
        TestThread2Runnable t3 = new TestThread2Runnable("https://cdn.lixingyong.com/2021/10/28/t011163ac77ca558ca5.jpg", "test3.jpg");

        //先下载t1.
        new Thread(t1).start();
        //然后是t2.
        new Thread(t2).start();
        //最后是t3.
        new Thread(t3).start();
    }
}

//下载器
class WebDownloaderRunnable{
    //下载方法
    public void downloader(String url, String name){
        try {
            FileUtils.copyURLToFile(new URL(url), new File(name));
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println("IO异常，downloader方法出现问题");
        }
    }
}